#include <stdio.h>
#include <stdlib.h>



int get_call_stack(void** retaddrs,int size);

struct stack_frame{
  struct stack_frame* next;//pointeur sur la prochaine frame
  void* ret;//adresse de retour de la frame
};

void* malloc(size_t size){
  
  void* retaddrs[10];
  
  printf("@ retaddrs=%p\n",retaddrs);
  int sz = get_call_stack(retaddrs,10);
  
  printf("taille de la pile des appels: %d\n",sz);
  
  for(int i=0;i<sz;i++){
    printf("@ %d = %p\n",i,retaddrs[i]);
  }
  
  return NULL;
}

int get_call_stack(void** retaddrs,int size){
  

  register struct stack_frame* fp asm("ebp");
  
  struct stack_frame* frame =fp;
  
  int i=0;
  //le dernier élément du tableau est l'adresse de debut de la pile
  while(frame){
    if(i < size){
      retaddrs[i++]=frame->ret; 
    }
    frame = frame->next;
  }
  return i;
}


int do_mallocs(){
  malloc(100);
  return 0;
}

int main(void){

  
  printf("Stack walking from ameziane\n");
  do_mallocs();
 
  return 0;
}
